package com.yangyang.androidconnect.websocket;

import android.util.Log;

import org.apache.commons.io.IOUtils;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;

public class MyWebSocketServer extends WebSocketServer {

    public MyWebSocketServer(int port) {
        super(new InetSocketAddress(port));
    }

    @Override
    public void onStart() {

    }

    @Override
    public void onOpen(WebSocket conn, ClientHandshake handshake) {
        Log.d("WebSocketServer", "New connection opened.");
    }

    @Override
    public void onClose(WebSocket conn, int code, String reason, boolean remote) {
        Log.d("WebSocketServer", "Connection closed.");
    }

    @Override
    public void onMessage(WebSocket conn, String message) {
        try {
            // 假设前端传递的消息格式为 "getMedia:path/to/file"
            if (message.startsWith("getMedia:")) {
                String filePath = message.substring("getMedia:".length());
                sendMedia(conn, filePath);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
//        try {
//            if (message.equals("getImage")) {
//                sendImage(conn);
//            } else if (message.equals("getVideo")) {
//                sendVideo(conn);
//            }
//        } catch (Throwable e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        Log.e("WebSocketServer", "Error: " + ex.getMessage());
    }


    private void sendMedia(WebSocket conn, String filePath) throws IOException {
        try (FileInputStream mediaStream = new FileInputStream(filePath)) {
//            byte[] buffer = new byte[1024];
//            int bytesRead;
//            while ((bytesRead = mediaStream.read(buffer)) != -1) {
//                conn.send(buffer);
//            }
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            IOUtils.copy(mediaStream,stream);
            conn.send(stream.toByteArray());
        }
    }

    private void sendImage(WebSocket conn) throws IOException {
        try (FileInputStream imageStream = new FileInputStream("/path/to/your/image.jpg")) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = imageStream.read(buffer)) != -1) {
                conn.send(buffer);
            }
        }
    }

    private void sendVideo(WebSocket conn) throws IOException {
        try (FileInputStream videoStream = new FileInputStream("/path/to/your/video.mp4")) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = videoStream.read(buffer)) != -1) {
                conn.send(buffer);
            }
        }
    }
}